<?php
namespace app\admin\controller\develop;
use app\admin\controller\Controller;
use Cron\CronExpression;
use app\admin\model\develop\Crontab as CrontabModel;
/**
 *  定时任务管理器
 * Class Crontab
 * @package app\admin\controller\develop
 */
class Crontab extends Controller
{

    /**
     * 查看
     */
    public function index()
    {
        $model = new CrontabModel;
        $list = $model->getList();
        $time = time();
        foreach ($list as $k => &$v) {
            $cron = CronExpression::factory($v['schedule']);
            $v['nexttime'] = $time > $v['endtime'] ?'无' : $cron->getNextRunDate()->getTimestamp();
        }
        return $this->fetch('index', compact('list'));
    }


    public function add(){
        $model = new CrontabModel;
        if (!$this->request->isAjax()) {
            // 类型
            $type = $model::getTypeList();
            return $this->fetch('add', compact('type'));
        }
        // 新增记录
        if ($model->add($this->postData('row'))) {
            return $this->renderSuccess('添加成功', url('develop.crontab/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }


    public function edit(){
        return $this->fetch('edit');
    }


    /**
     * 判断Crontab格式是否正确
     * @internal
     */
    public function check_schedule()
    {
        $row = $this->request->post("row/a");
        $schedule = isset($row['schedule']) ? $row['schedule'] : '';
        if (CronExpression::isValidExpression($schedule)) {
            $this->success();
        } else {
            $this->error('Crontab格式错误');
        }
    }

    /**
     * 根据Crontab表达式读取未来七次的时间
     * @internal
     */
    public function get_schedule_future()
    {
        $time = [];
        $schedule = $this->request->post('schedule');
        $days = (int)$this->request->post('days');
        try {
            $cron = CronExpression::factory($schedule);
            for ($i = 0; $i < $days; $i++) {
                $time[] = $cron->getNextRunDate(null, $i)->format('Y-m-d H:i:s');
            }
        } catch (\Exception $e) {

        }

        $this->success("", null, ['futuretime' => $time]);
    }

}

